<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="onSearch"
        />
        <!-- 树形组件 -->
        <!-- 指定高亮 点击谁谁就高亮设置  setCurrentKey指定高亮需要传key -->
        <!--current-change 当前选中节点变化时触发的事件-->
        <el-tree
          ref="treeRef"
          node-key="id"
          highlight-current
          :props="{ label: 'name' }"
          default-expand-all
          :data="list"
          :expand-on-click-node="false"
          @current-change="onChangeDepID"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="add-employee" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-permission="importEmployee" size="mini" @click="showExcel">excel导入</el-button>
          <el-button v-permission="exportEmployee" size="mini" @click="onExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table v-loading="loading" :data="tableList">
          <el-table-column label="头像" prop="staffPhoto">

            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>

          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ row.formOfEmployment===1?'正式':'非正式' }}
            </template>

          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" @click="$router.push('/employee/detail/'+row.id)">查看</el-button>
              <el-button type="text" @click="onShow(row.id)">角色</el-button>

              <el-popconfirm title="确定删除吗？" @onConfirm="confirm(row.id)">

                <el-button slot="reference" type="text">删除</el-button>

              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="handleCurrentChange"
          />
        </el-row>

      </div>
    </div>
    <!-- 弹出层 -->
    <el-dialog :visible.sync="visible" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in dialogList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row type="flex" justify="center">
        <el-button size="mini" type="primary" @click="onUpdateRole">确定</el-button>
        <el-button size="mini">取消</el-button>
      </el-row>
    </el-dialog>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @onSuccess="fn" />
  </div>
</template>

<script>
let typeID = 1
import { getDespAPi } from '@/api/department'
import { saveAs } from 'file-saver'
import { list2Tree } from '@/utils'
import { delEmployeesAPI, ExportEmployeeAPI, getEmployeeAPI, reviseEmployeeAPI } from '@/api/employee'
import importExcel from './components/import-excel.vue'
import { assignRole, getEnableRolesAPI } from '@/api/role'
export default {

  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      // 弹出层的数组
      dialogList: [],
      roleIds: [], // 用来双向绑定数据的
      userId: null, // 用来记录当前点击的用户id
      visible: false,
      list: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 定义一个员工id
      depId: null,
      // 用来定义渲染表格
      tableList: [],
      page: null,
      total: 1,
      // 定义一个变量 用来做模糊查询
      keyword: '',
      loading: false,
      showExcelDialog: false
    }
  },
  // 发送获取树形结构数据请求
  async created() {
    const res = await getDespAPi()
    // console.log(res)
    // 转树 成功后 指定第一个高亮 获取员工id
    this.list = list2Tree(res.data, 0)
    this.depId = this.list[0].id
    // 刷新页面
    this.onLoadEmployee()
    // console.log(this.list)
    this.$nextTick(() => {
      this.$refs.treeRef.setCurrentKey(this.list[0].id)
    })
  },
  methods: {
    // 点击弹出层的确定，更新数据
    async onUpdateRole() {
      await assignRole({ id: this.userId, roleIds: this.roleIds })
      this.$message.success('更新成功')
      this.visible = false
    },
    // 点击角色 打开弹出层 发送请求 定义一个数组接收数据 渲染到弹出层 给复选框双向绑定id 因为要接收点击后的id，而不是每个复选框的id
    async onShow(id) {
      console.log(id)
      const { data } = await getEnableRolesAPI()
      this.dialogList = data
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.userId = id
      const res = await reviseEmployeeAPI(id)
      console.log(res)
      this.roleIds = res.data.roleIds
      this.visible = true
    },
    // 点击删除
    async  confirm(id) {
      // console.log(id)
      await delEmployeesAPI(id)
      // 刷新 提示 长度判断
      this.$message.success('删除成功')
      this.onLoadEmployee()
      if (this.tableList.length === 0) {
        this.page--
      }
    },
    // 子组件添加成功 通知父组件刷新
    fn() {
      this.onLoadEmployee()
    },
    // 点击导入
    showExcel() {
      this.showExcelDialog = true
    },
    // 导出
    async onExport() {
      const res = await ExportEmployeeAPI()
      saveAs(res, '员工导出表.xlsx')
    },
    // 监听输入事件 做模糊查询 防抖防止多次触发请求(定义一个全局变量用来存储和清除)，增加浏览器负担
    onSearch() {
      clearTimeout(typeID)
      typeID = setTimeout(() => {
        this.onLoadEmployee()
      })
      this.page = 1
    },
    // 监听分页 点击页数实现相应跳转
    handleCurrentChange(page) {
      this.page = page
      // this.page = 1
      this.onLoadEmployee()
    },
    // 当选中当前节点通过员工id就渲染当前节点的员工的数据
    onChangeDepID(row) {
      // console.log(row)
      this.depId = row.id
      this.onLoadEmployee()
    },
    async onLoadEmployee() {
      this.loading = true
      const res = await getEmployeeAPI({ page: this.page, pagesize: 10, departmentId: this.depId, keyword: this.keyword })
      // console.log(res.data.rows)
      this.tableList = res.data.rows
      this.loading = false
      this.total = res.data.total
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
